package tool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.log4j.Logger;

import com.wechat.service.WechatService;

import net.sf.json.JSONObject;

/**
 *  微信工具类：
 *  下载图片  获取openid等
 *  
 *  注意：
 *  所有用到jssdk的页面必须用到注入对象 wxconfig 参见：WechatService
 *  
 *  待完善：
 *  将一些参数配置到xml文件中
 *  
 *  准备替换：ReadUrl ReadUrl2 
 *  
 * @author chz
 *
 */
public class WechatTool {

private static Logger logger = Logger.getLogger(WechatTool.class);

	/**使用实例
	 * @param args
	 * @throws Exception 
	 * 
		# xi bu gongcheng jixie
		wechat.url=http://we.51waji.com/wechat4j2/wexin
		wechat.token=dsofashfosfjsdkfh123914ujfgh
		wechat.encodingaeskey=TkNFOHnZf67elJPJfGIHb2mWNNGEJV62qeVxs1HBg23
		wechat.appid=wx3c0d18351a1111ec
		wechat.appsecret=dba48726cf3e6fe853a97ad952b40247
 
	 * 
	 */
	public static void main(String[] args) {
		
		
		// 由MEDIA_ID获取图片并保存到本地 限制：10000次／天
		String access_token0=WechatTool.getAccessToken();		//A) 这个是基础接口中的accessToken
		String url2="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
		WechatTool.download(url2, "filename", "/Users/chz/Desktop/tmp");
		
		// 拉取用户信息
		String code="?????";
		String appid="wx3c0d18351a1111ec";
		String secret="dba48726cf3e6fe853a97ad952b40247";//dba48726cf3e6fe853a97ad952b40247
		String url3="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
		url3.replace("CODE",code);
		url3.replace("APPID",appid);
		url3.replace("SECRET",secret);
		String _json=WechatTool.readUrl(url3);
		String openId=JSONObject.fromObject(_json).getString("openid");		// 由code获取openid
		String access_token=JSONObject.fromObject(_json).getString("access_token");		// B) 由code获取access_token
		 
		String url4="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
		url4.replace("ACCESS_TOKEN", access_token);
		url4.replace("OPENID",openId);
		String _json2=WechatTool.readUrl(url4);				// 由access_token拉取用户信息
		String nickname=JSONObject.fromObject(_json).getString("nickname");
		String headimgurl=JSONObject.fromObject(_json).getString("headimgurl");
		
	}
	
	/**
	 * 获取基础支持中的accessToken
	 * @return
	 */
	public static String getAccessToken(){
		return WechatService.getInstance().find().getAccessToken();
	}
	

	/**
	 * 从指定url加载json并提取argName对应的字段值
	 * @param url
	 * @param argName
	 * @return
	 */
	public static String loadJson(String url ,String argName){
		
		String json = readUrl(url);
		JSONObject jsonObject = JSONObject.fromObject(json);
		return jsonObject.getString(argName);

	}
	
	/**
	 * 读取访问指定url的返回字符串
	 * @param url
	 * @return
	 */
	public  static String readUrl (String url) {  
        StringBuilder json = new StringBuilder();  
        try {  
            URL urlObject = new URL(url);  
            URLConnection uc = urlObject.openConnection();  
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"UTF-8"));  
            String inputLine = null;  
            while ( (inputLine = in.readLine()) != null) {  
                json.append(inputLine);  
            }  
            in.close();  
        } catch (MalformedURLException e) { 
        	logger.info("loadJson失败");
            e.printStackTrace(); 
            return null;
        } catch (IOException e) { 
        	logger.info("loadJson失败");
            e.printStackTrace(); 
            return null;
        }  
        return json.toString();  
    } 
	
	/**
	 * 下载url文件到本地
	 * @param urlString	
	 * @param filename	重命名的文件名
	 * @param savePath 保存位置
	 * @throws Exception
	 */
	public static void download(String urlString, String filename,String savePath) {
		try{
		// 构造URL
	    URL url = new URL(urlString);
	   
	    // 打开连接
	    URLConnection con = url.openConnection();
	    //设置请求超时为5s
	    con.setConnectTimeout(5*1000);
	    // 输入流
	    InputStream is = con.getInputStream();
	
	    // 1K的数据缓冲
	    byte[] bs = new byte[1024];
	    // 读取到的数据长度
	    int len;
	    // 输出的文件流
	   File sf=new File(savePath);
	   if(!sf.exists()){
		   sf.mkdirs();
	   }
	   //OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);   //for windows
	   OutputStream os = new FileOutputStream(sf.getPath()+"/"+filename);
	    // 开始读取
	    while ((len = is.read(bs)) != -1) {
	      os.write(bs, 0, len);
	    }
	    // 完毕，关闭所有链接
	    os.close();
	    is.close();
	   }catch(Exception e){
		   logger.info("download失败:"+urlString);
	   }
	} 
	
	

}
